package com.bonana.core.services.impl;

import com.bonana.core.dao.CustomMapper;
import com.bonana.core.dao.project.*;
import com.bonana.core.dao.index.IndexProjectMapper;
import com.bonana.core.dao.user.CoreUserProfileDAO;
import com.bonana.core.entity.CoreUserProfile;
import com.bonana.core.entity.mybatis.*;
import com.bonana.core.result.Response;
import com.bonana.core.result.ResponseCode;
import com.bonana.core.services.ProjectService;
import com.bonana.core.vo.OperStatusVO;
import com.bonana.core.vo.ProjectCommentVo;
import com.bonana.core.vo.ProjectVoteVo;
import com.bonana.utils.TimeDifferenceTool;
import com.bonana.utils.TimestampUtil;
import com.github.pagehelper.PageHelper;
import com.google.common.net.InetAddresses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by Administrator on 2016/7/4.
 */
@Service
public class ProjectServiceImpl implements ProjectService{
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    IndexProjectMapper indexMapper;
    @Autowired
    CustomMapper customMapper;
    @Autowired
    VoteLogMapper voteMapper;
    @Autowired
    ProjectFavLogMapper favProjMapper;
    @Autowired
    CoreUserProfileDAO userProfileDAO;
    @Autowired
    ProjectAlbumMapper projectAlbumMapper;
    @Autowired
    ProjectActiveMapper activeMapper;
    @Autowired
    ProjectCommentMapper commentMapper;
    @Autowired
    ProjectVisitorMapper visitorMapper;

    @Override
    public int addProject(Project proj) {
        return projectMapper.insert(proj);
    }

    @Override
    public int delProjectById(int projId) {
        return projectMapper.deleteByPrimaryKey(projId);
    }

    @Override
    public int updateProject(Project proj) {
        return projectMapper.updateByPrimaryKeySelective(proj);
    }

    @Override
    public Project getProjectById(int projId) {
        return projectMapper.selectByPrimaryKey(projId);
    }

    @Override
    public List<Project> getProjs(int pgNum, int pgSize, String query) {
        ProjectExample example = new ProjectExample();
        if(query != null && !"".equals(query)){
            example.createCriteria().andProjectNameLike("%"+query+"%");
        }
        PageHelper.startPage(pgNum, pgSize);
        example.setOrderByClause("project_createtime desc");
        List<Project> list = projectMapper.selectByExample(example);
        return list;
    }

    @Override
    public List<Project> getIndexProjs() {
        return customMapper.getIndexProjects(8);
    }

    @Override
    public int RemoveFromIndex(int projId) {
        return indexMapper.deleteByPrimaryKey(projId);
    }

    @Override
    public int AddToIndex(IndexProject projId) {
        projId.setAddTime(new java.util.Date());
        return indexMapper.insert(projId);
    }

    @Override
    public Response voteForProject(int projId, int uid, String usource) {
        try {
            VoteLog userVote = new VoteLog();
            userVote.setVoterId(uid);
            userVote.setProjectId(projId);
            userVote.setVoterIp(InetAddresses.coerceToInteger(InetAddresses.forString(usource)));
            userVote.setVoterTime(TimestampUtil.now());
            voteMapper.insert(userVote);
            Project proj = projectMapper.selectByPrimaryKey(projId);
            proj.setProjectVotecnt(proj.getProjectVotecnt()+1);
            projectMapper.updateByPrimaryKey(proj);
            return new Response(ResponseCode.SUCC);
        } catch (Exception e) {
            return  new Response(ResponseCode.ALREADY_FOLLOWED);
        }

    }

    public Response FavProject(int projId, int uid) {
        ProjectFavLog key = new ProjectFavLog();
        key.setProjectId(projId);
        key.setUid(uid);
        key.setAddTime(new Date());
        try {
            favProjMapper.insert(key);
            Project proj = projectMapper.selectByPrimaryKey(projId);
            proj.setProjectLikecnt(proj.getProjectLikecnt()+1);
            projectMapper.updateByPrimaryKey(proj);
            return new Response(ResponseCode.SUCC);
        } catch(Exception e){
            return  new Response(ResponseCode.ALREADY_LIKED);
        }
    }

    @Async
    public void IncProjectViewCnt(int projId, int uid) {
        Project proj = projectMapper.selectByPrimaryKey(projId);
        proj.setProjectViewcnt(proj.getProjectViewcnt()+1);
        projectMapper.updateByPrimaryKey(proj);
        if (uid > 0) {
            ProjectVisitor pv = new ProjectVisitor();
            pv.setVisitTime(new Date());
            pv.setProjectId(projId);
            pv.setUid(uid);
            try {
               visitorMapper.insert(pv);
            } catch (Exception e) {

            }
        }
    }

    @Override
    public List<VoteLog> getProjectVote(int projId) {
        VoteLogExample voteex = new VoteLogExample();
        voteex.createCriteria().andProjectIdEqualTo(projId);
        return voteMapper.selectByExample(voteex);
    }

    @Override
    public List<ProjectActive> getProjectActiveByPId(int projId) {
        ProjectActiveExample ex = new ProjectActiveExample();
        ex.createCriteria().andProjectIdEqualTo(projId);
        ex.setOrderByClause("create_time desc");
        List<ProjectActive> ret =  activeMapper.selectByExample(ex);
        for (ProjectActive pa:ret) {
            pa.setDateDes(TimeDifferenceTool.showDateString(pa.getCreateTime()));
        }
        return ret;
    }

    @Override
    public int addProjActive(ProjectActive pa) {
        if (pa.getActiveId()==0) {
            return activeMapper.insert(pa);
        }else{
            return activeMapper.updateByPrimaryKeySelective(pa);
        }
    }

    @Override
    public int delProjActive(int activeId) {
        return activeMapper.deleteByPrimaryKey(activeId);
    }

    @Override
    public ProjectActive getActiveById(int activeId) {
        return activeMapper.selectByPrimaryKey(activeId);
    }

    @Override
    public List<ProjectCommentVo> getProjectCommentsbyPid(int projId,int pgNum, int pgSize) {
        PageHelper.startPage(pgNum, pgSize);
        List<ProjectCommentVo> retRes = customMapper.getProjectComments(projId);
        for (ProjectCommentVo vo:retRes) {
            vo.setDateDes(TimeDifferenceTool.showDateString(vo.getCreatedTime()));
            List<ProjectCommentVo> reps = customMapper.getChildComments(vo.getCommentId());
            for (ProjectCommentVo pcv:reps) {
                pcv.setDateDes(TimeDifferenceTool.showDateString(pcv.getCreatedTime()));
            }
            vo.setReplays(reps);
        }
        return retRes;
    }

    @Override
    public List<ProjectVoteVo> getProjectVotesByPid(int projId, int pgNum, int pgSize) {
        PageHelper.startPage(pgNum, pgSize);
        List<ProjectVoteVo> retRes = customMapper.getProjectVote(projId);
        return retRes;
    }

    @Override
    public int addComment(int projId, int sender, int parrendId, String content) {
        ProjectComment comment = new ProjectComment();
        comment.setProjectId(projId);
        comment.setContent(content);
        comment.setCreatedTime(new Date());
        comment.setParentId(parrendId);
        comment.setUid(sender);
        comment.setIsDeleted(false);
        return commentMapper.insert(comment);
    }

    @Override
    public List<CoreUserProfile> getProjectRecentVisitor(int projId, int cnt) {
        if (cnt <= 0) {
            cnt = 6;
        }
        return customMapper.getProjectRecentVisitor(projId, cnt);
    }

    @Override
    public List<Project> getHotProjects(int cnt) {
        return customMapper.getHotProjects(cnt);
    }

    @Override
    public OperStatusVO getRelation(int projId, int uid) {
        OperStatusVO status = new OperStatusVO();
        status.setFollowed(false);
        status.setLiked(false);
        status.setVoted(false);
        if (uid == 0) {
            return status;
        }
        ProjectFavLogKey favKey = new ProjectFavLog();
        favKey.setProjectId(projId);
        favKey.setUid(uid);
        if (favProjMapper.selectByPrimaryKey(favKey) != null) {
            status.setLiked(true);
        }
        VoteLogExample voteKey = new VoteLogExample();
        voteKey.createCriteria().andProjectIdEqualTo(projId).andVoterIdEqualTo(uid);
        if (voteMapper.selectByExample(voteKey) != null) {
            status.setVoted(true);
        }
        return status;
    }
}
